<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use Workerman\Worker;
use PHPSocketIO\SocketIO;

class Jpush extends Command
{
    protected $member = [];
    
    protected $sender_io = null;
    
    protected $Startup = ['start', 'stop', 'restart', 'reload', 'status'];
    
    protected function configure()
    {
        $this->setName('jpush')
            ->addArgument('Startup', Argument::OPTIONAL, "liunx Startup state: start、stop、restart、reload、status")
            ->addOption('option', null, Option::VALUE_REQUIRED, 'liunx debug or Daemon; insert: true | false')
            ->setDescription('web socket; liunx Startup: php think jpush start --option=true; window Startup: php think jpush');
    }

    protected function execute(Input $input, Output $output)
    {
        if(PATH_SEPARATOR==':'){
            global $argv;
            $Startup = trim($input->getArgument('Startup'));
            if(!in_array($Startup, $this->Startup)) {
                return $output->write('liunx Startup state: start、stop、restart、reload、status');
            }
            $argv[0] = 'think jpush';
            $argv[1] = $Startup;
            if($input->hasOption('option')) {
                if($input->getOption('option')=='true') {
                    $argv[2] = '-d';
                }
            }
        }
        
        $this->sender_io = new SocketIO(config('jshop.socket_port'));
        
    	$this->sender_io->on('connection', array($this, 'onConnection'));
        
        $this->sender_io->on('workerStart', array($this, 'onWorkerStart'));
        
        worker::runAll();
    }
    
    public function onConnection($socket)
    {
        $socket->emit('msg', '连接成功');
    }
    
    public function onWorkerStart()
    {
        $http_worker = new Worker(config('jshop.http_bin_host'));
        $http_worker->onMessage = array($this, 'onHttpMessage');
        $http_worker->listen();
    }
    
    public function onHttpMessage($http_connect, $data)
    {
        switch ($data['post']['method']) {
            case 'liquor_order':
                $res = $this->sendLiquorOrder($data);
                break;
            case 'pay_bill':
                $res = $this->sendPayBill($data);
                break;
            case 'rechange':
                $res = $this->sendRechange($data);
                break;
            default:
                $res = $this->sendOrder($data);
        }
        $http_connect->send($res);
    }
    
    private function sendOrder($data)
    {
        $order_model = new \app\common\model\Order();
        $order_info = $order_model::with(['items', 'user'])->where('order_id', $data['post']['id'])->find();
		if(!$order_info) {
			return '查无此单';
		}
        //处理昵称
        $nickname = explode('****', $order_info->user->nickname);
        if(count($nickname) > 1) {
            $nickname = '手机'.num_zh($nickname[0]).'尾号'.num_zh($nickname[1]);
        } else {
            $nickname = $order_info->user->nickname;
        }
        $order_item = obj_to_array($order_info->items);
        $goods_id_arr = array_column($order_item, 'goods_id');
        $goods_model = new \app\common\model\Goods();
        $goods_list = $goods_model->where('id', 'in', $goods_id_arr)->field(['id', 'name','company'])->select();
        $goods_list = arr_key($goods_list, 'id');
        $goods_name_str = '';
        foreach ($order_item as $info) {
            $goods_name_str .= brackets_filter($info['name']);
            if(!empty($goods_list[$info['goods_id']]['company'])) {
                $goods_name_str .= $info['nums'].$goods_list[$info['goods_id']]['company'];
            }
            $goods_name_str .= '，';
        }
        $sendMsg = [];
        $sendMsg['state'] = true;
        $sendMsg['notice'] = "用户{$nickname}。 {$order_info->room_bn}房间，下单购买{$goods_name_str}单价：{$order_info->order_amount}元、请尽快打单出酒。";
        $sendMsg['url'] = '/manage/order/index.html';
        $this->sender_io->emit('notice', json_encode($sendMsg));
		return '推送成功';
    }
    
    private function sendLiquorOrder($data)
    {
        $liquor_model = new \app\common\model\LiquorOrder();
        $liquor_info = $liquor_model->get($data['post']['id'], ['user', 'liquor']);
		if(!$liquor_info) {
			return '查无此单';
		}
        //
        $sendMsg = [];
        $sendMsg['state'] = true;
        $goods_name = brackets_filter($liquor_info->liquor->goods_name);
        $sendMsg['notice'] = "用户{$liquor_info->user->nickname}。 {$liquor_info->room_bn}房间，下单取{$goods_name} {$liquor_info->number}瓶，请尽快打单出酒。";
        $sendMsg['url'] = '/manage/liquor/index.html';
        $this->sender_io->emit('notice', json_encode($sendMsg));
		return '推送成功';
    }
    
    private function sendPayBill($data)
    {
        $pay_bill_model = new \app\common\model\PayBill();
        $pay_bill_info = $pay_bill_model->get($data['post']['id'], 'user');
		if(!$pay_bill_info) {
			return '查无此单';
		}
        //
        $sendMsg = [];
        $sendMsg['state'] = true;
        $sendMsg['notice'] = "用户{$pay_bill_info->user->nickname}。 {$pay_bill_info->room_bn}房间，结账埋单{$pay_bill_info->amount}元，请尽快打单。";
        $sendMsg['url'] = '/manage/liquor/index.html';
        $this->sender_io->emit('notice', json_encode($sendMsg));
		return '推送成功';
    }
    
    public function sendRechange($data)
    {
        $rechange_model = new \app\common\model\Rechange();
        $rechange_info = $rechange_model->get($data['post']['id'], 'user');
		if(!$rechange_info) {
			return '查无此单';
		}
        //
        $sendMsg = [];
        $sendMsg['state'] = true;
        $sendMsg['notice'] = "用户{$rechange_info->user->nickname}。 充值{$rechange_info->amount}元成功。请尽快处理";
        $sendMsg['url'] = '/manage/rechange/index.html';
        $this->sender_io->emit('notice', json_encode($sendMsg));
		return '推送成功';
    }
}
